<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha256-AbA177XfpSnFEvgpYu1jMygiLabzPCJCRIBtR5jGc0k=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"fengxun2017.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.13.2","exturl":false,"sidebar":{"position":"right","display":"hide","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文介绍使用Task Notification，在一些常见开发场景中来替代二值信号量、计数信号量、event group、以及消息邮箱（存储单个uint32_t数值的邮箱），以提高系统运行效率。">
<meta property="og:type" content="article">
<meta property="og:title" content="FreeRTOS-使用 task notification">
<meta property="og:url" content="http://fengxun2017.github.io/2023/02/13/FreeRTOS-use-task-notification/index.html">
<meta property="og:site_name" content="fx">
<meta property="og:description" content="本文介绍使用Task Notification，在一些常见开发场景中来替代二值信号量、计数信号量、event group、以及消息邮箱（存储单个uint32_t数值的邮箱），以提高系统运行效率。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-12T16:00:00.000Z">
<meta property="article:modified_time" content="2023-02-17T15:43:06.427Z">
<meta property="article:author" content="feng xun">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://fengxun2017.github.io/2023/02/13/FreeRTOS-use-task-notification/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://fengxun2017.github.io/2023/02/13/FreeRTOS-use-task-notification/","path":"2023/02/13/FreeRTOS-use-task-notification/","title":"FreeRTOS-使用 task notification"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>FreeRTOS-使用 task notification | fx</title>
  






  <script async defer data-website-id="" src=""></script>

  <script defer data-domain="" src=""></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
  <a target="_blank" rel="noopener" href="https://github.com/fengxun2017" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">fx</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-%E4%BD%BF%E7%94%A8Task-Notifacation-%E6%A8%A1%E6%8B%9F%E4%BA%8C%E5%80%BC%E4%BF%A1%E5%8F%B7%E9%87%8F"><span class="nav-number">1.</span> <span class="nav-text">1 使用Task Notifacation 模拟二值信号量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-%E4%BD%BF%E7%94%A8Task-Notifacation-%E6%A8%A1%E6%8B%9F%E8%AE%A1%E6%95%B0%E4%BF%A1%E5%8F%B7%E9%87%8F"><span class="nav-number">2.</span> <span class="nav-text">2 使用Task Notifacation 模拟计数信号量</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-%E4%BD%BF%E7%94%A8Task-Notifacation-%E6%A8%A1%E6%8B%9F-event-group"><span class="nav-number">3.</span> <span class="nav-text">3 使用Task Notifacation 模拟 event group</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8Task-Notifacation-%E4%BD%9C%E4%B8%BA%E4%B8%80%E4%B8%AA%E8%BD%BB%E9%87%8F%E7%BA%A7%E6%B6%88%E6%81%AF%E9%82%AE%E7%AE%B1"><span class="nav-number">4.</span> <span class="nav-text">使用Task Notifacation 作为一个轻量级消息邮箱</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">feng xun</p>
  <div class="site-description" itemprop="description">FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">96</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
  </nav>
</div>
  <div class="cc-license site-overview-item animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" class="cc-opacity" rel="noopener" target="_blank"><img src="https://cdnjs.cloudflare.com/ajax/libs/creativecommons-vocabulary/2020.11.3/assets/license_badges/small/by_nc_sa.svg" alt="Creative Commons"></a>
  </div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://fengxun2017.github.io/2023/02/13/FreeRTOS-use-task-notification/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="feng xun">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="fx">
      <meta itemprop="description" content="FreeRTOS交流QQ群-663806972 BLE学习交流群-498676838">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="FreeRTOS-使用 task notification | fx">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          FreeRTOS-使用 task notification
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-02-13 00:00:00" itemprop="dateCreated datePublished" datetime="2023-02-13T00:00:00+08:00">2023-02-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/FreeRTOS/" itemprop="url" rel="index"><span itemprop="name">FreeRTOS</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>11k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>14 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center>
本文介绍使用Task Notification，在一些常见开发场景中来替代二值信号量、计数信号量、event group、以及消息邮箱（存储单个uint32_t数值的邮箱），以提高系统运行效率。
</center>


<span id="more"></span>

<hr>
<p>使用<code>Task Notification</code>需要在工程配置文件<code>FreeRTOSConfig.h</code>中定义:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">define</span> configUSE_TASK_NOTIFICATIONS	1</span></span><br></pre></td></tr></table></figure>
<p>在文章<a href="https://fengxun2017.github.io/2023/02/07/FreeRTOS-task-notification/">FreeRTOS-Task Notification</a>中，我们提到在FreeRTOS版本<code>FreeRTOSv202112</code>之后，内核任务控制块结构的<code>Task Notification</code>储存区，不再是仅能存储单个<code>uint32_t</code> 值，而是定义为一个可配置的数据 <code>uint32_t ulNotifiedValue [ configTASK_NOTIFICATION_ARRAY_ENTRIES ]</code>（默认配置大小为1）。</p>
<p>因此，如果有需求，可以将数组设置更大，使得<code>Task Notifacation</code>可以存储多个 <code>uint32_t</code>值，每个值用作不同的目的。</p>
<p><code>Task Notification</code>提供的API，每次仅能读&#x2F;写<code>ulNotifiedValue</code>数组中的单个值。因此，<code>Task Notification</code>的 API 中包含一个<code>index</code>参数用来指定操作数组中的哪个值。同时，为了和历史版本的<code>Task Notification</code>兼容，也保留了旧版本中不需要指定<code>index</code>参数的 API（因为旧版本中就是单个uint32_t值），它们操作<code>ulNotifiedValue</code>中的第 <strong>0</strong> 个值:</p>
<p>例如，两个发送数据相关的API:<br>xTaskNotify——默认是将数据写入到目标任务<code>ulNotifiedValue</code>数组中的第<strong>0</strong>个值。<br>xTaskNotifyIndexed——需要指定数据是写入目标任务<code>ulNotifiedValue</code>数组中的哪个值。</p>
<p>例如，两个获取数据相关的API：<br>ulTaskNotifyTake——默认是获取目标任务<code>ulNotifiedValue</code>数组中的第 <strong>0</strong> 个值。<br>ulTaskNotifyTakeIndexed——需要指定获取目标任务<code>ulNotifiedValue</code>数组中的哪个值。</p>
<p>在下文中，我们均使用不需要指定<code>index</code>参数的API，即操作<code>ulNotifiedValue</code>数组中的第 <strong>0</strong> 个值。<br>后文中提及的<code>ulNotifiedValue</code>也默认指的是该数组的第 <strong>0</strong> 个值，而不是实际的数组。</p>
<h4 id="1-使用Task-Notifacation-模拟二值信号量"><a href="#1-使用Task-Notifacation-模拟二值信号量" class="headerlink" title="1 使用Task Notifacation 模拟二值信号量"></a>1 使用Task Notifacation 模拟二值信号量</h4><p><a href="https://fengxun2017.github.io/2022/12/15/FreeRTOS-use-binary-semaphore/">二值信号量</a>的外在表现就是两种状态：</p>
<ul>
<li><strong>值为0</strong>： 表示不可用，此时如果任务请求获取信号量，就会进入阻塞状态，等待其可用（当设置了等待超时时间）。</li>
<li><strong>值为1</strong>：表示可用。此时任务请求信号量时，可以立刻获得，并且信号量会变为不可用状态（值为0）</li>
</ul>
<p>当使用<code>Task Notification</code>来模拟二值信号量时，API：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">uint32_t</span> <span class="title function_">ulTaskNotifyTake</span><span class="params">( BaseType_t xClearCountOnExit, TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<p>可以用来模拟任务<strong>获取信号量</strong>，实际上该函数内部实现是等待任务自身控制块中的<code>ulNotifiedValue</code>值<strong>大于</strong>0。调用该函数时如果<code>ulNotifiedValue</code>的值：</p>
<ul>
<li><strong>等于0</strong>，可以认为当前“信号量不可用”，任务会阻塞并等待其值大于0（参数<code>xTicksToWait</code>为等待时间）。</li>
<li><strong>大于0</strong>，可以看做“信号量可用”了，该函数成功返回（等于拿到信号量），而二值信号量的特性是一旦被获取，就会再次变为“不可用状态”。为了实现该特性，该函数的参数<code>xClearCountOnExit</code>需要指定为<code>pdTRUE</code>，表示成功获取到非0值时，就将任务控制块中的<code>ulNotifiedValue</code>归零（变为“不可用状态”）。</li>
</ul>
<br>

<p>用来模拟<strong>设置信号量</strong>的 API为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xTaskNotifyGive</span><span class="params">( TaskHandle_t xTaskToNotify )</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 中断处理函数中调用时，需要使用中断版本：</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">vTaskNotifyGiveFromISR</span><span class="params">( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>参数<code>xTaskToNotify</code>：为目标任务句柄。该函数内部实现就是将目标任务控制块中的<code>ulNotifiedValue</code>值加1（非0，变为可用了）。如果目标任务当前正在等待“信号量可用”（等待<code>ulNotifiedValue</code>值<strong>大于</strong>0），那么调用该API 会使得目标任务恢复为就绪态。</li>
<li>参数<code>pxHigherPriorityTaskWoken</code>：作用见下文代码中的注释。</li>
</ul>
<p>我们用上述两个API，来实现<a href="https://fengxun2017.github.io/2022/12/15/FreeRTOS-use-binary-semaphore/">二值信号量</a>一文中的任务等待按键事件：</p>
<p>任务代码和main函数如下所示：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdint.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdbool.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;SEGGER_RTT.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">button_pressed_handler</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="comment">// 使用portMAX_DELAY，表示一直等待直到可用。</span></span><br><span class="line">        <span class="comment">// 使用portMAX_DELAY，需要在FreeRTOSConfig.h 文件中定义 INCLUDE_vTaskSuspend = 1</span></span><br><span class="line">        <span class="comment">// 正式产品代码最好使用一个超时值，这样异常发生时（中断源发生异常，没按预期触发），至少能获得超时错误，可以在超时错误中做一些恢复操作。</span></span><br><span class="line">        ulTaskNotifyTake(pdTRUE, portMAX_DELAY);</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in task, do something\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">TaskHandle_t  pxCreatedTask;</span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    bsp_init();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">// pxCreatedTask 保存创建的任务button_pressed_handler的句柄。</span></span><br><span class="line">    <span class="comment">// 向任务button_pressed_handler发送notification时，需要该值指明任务。</span></span><br><span class="line">    <span class="keyword">if</span> (pdPASS == xTaskCreate(button_pressed_handler, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">1</span>, &amp;pxCreatedTask))&#123;</span><br><span class="line">        </span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">        vTaskStartScheduler();</span><br><span class="line">    &#125; </span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>按键中断处理函数中调用通知 API：<code>vTaskNotifyGiveFromISR</code></p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 目标任务的句柄</span></span><br><span class="line"><span class="keyword">extern</span> TaskHandle_t  pxCreatedTask;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在自己硬件平台的按键中断处理函数中调用 vTaskNotifyGiveFromISR 即可</span></span><br><span class="line"><span class="type">void</span> <span class="title function_">GPIOTE_IRQHandler</span><span class="params">(<span class="type">void</span>)</span>&#123;</span><br><span class="line"></span><br><span class="line">    BaseType_t higher_task_woken = pdFALSE;</span><br><span class="line">    <span class="keyword">if</span> ( NRF_GPIOTE-&gt;EVENTS_PORT == <span class="number">1</span> )&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//中断处理函数中要清除event,不然会导致一直产生中断</span></span><br><span class="line">        NRF_GPIOTE-&gt;EVENTS_PORT = <span class="number">0</span>;    </span><br><span class="line"></span><br><span class="line">        <span class="comment">// 确认是按键按下，则设置信号量</span></span><br><span class="line">        <span class="keyword">if</span>(IS_BUTTON_PRESSED(BUTTON_1)) &#123;</span><br><span class="line">            vTaskNotifyGiveFromISR(pxCreatedTask, &amp;higher_task_woken);</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in interrupt service function, button pressed\n&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果higher_task_woken=True，表示有更高优先级任务就绪了</span></span><br><span class="line">    <span class="comment">// 我们使用的是抢占式调度，只要有更高优先级的任务就绪，应该让其立刻运行。</span></span><br><span class="line">    <span class="comment">// 下面的代码就是，判断有更高优先级就绪时，就会设置任务切换中断，那么当前中断函数退出后，就会立刻触发任务切换，让最高优先级的就绪任务运行。</span></span><br><span class="line">    portYIELD_FROM_ISR(higher_task_woken);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>运行如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">in interrupt service function, button pressed</span><br><span class="line">in task, do something</span><br><span class="line">in interrupt service function, button pressed</span><br><span class="line">in task, do something</span><br></pre></td></tr></table></figure>

<h4 id="2-使用Task-Notifacation-模拟计数信号量"><a href="#2-使用Task-Notifacation-模拟计数信号量" class="headerlink" title="2 使用Task Notifacation 模拟计数信号量"></a>2 使用Task Notifacation 模拟计数信号量</h4><p>二值信号量的特性是：非 “<strong>0</strong>” 即 “<strong>1</strong>” ，信号量一旦被获取，立刻又会变为不可用状态（“0”）。因此，我们在使用<code>ulTaskNotifyTake(  xClearCountOnExit,  xTicksToWait )</code>模拟获取信号量时，设置参数<code>xClearCountOnExit = pdTRUE</code>，使其实现“信号量被获取后就立刻变为不可用”。也是因为该特性，二值信号量不具备计数特性。</p>
<p><a href="https://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/">计数信号量</a>相比二值信号量多了计数功能。<br>使用<code>Task Notification</code>模拟计数信号量的方式和上文一样，只是在调用</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">uint32_t</span> <span class="title function_">ulTaskNotifyTake</span><span class="params">( BaseType_t xClearCountOnExit, TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<p>时，设置参数<code>xClearCountOnExit = pdFALSE</code>，这样该函数的行为就是将目标任务控制块中的<code>ulNotifiedValue</code>值<strong>减 1</strong>（没有清零，如果“信号量”被设置多次，那么就可以调用对应次数的<code>ulTaskNotifyTake</code>，每次都能立刻获得到“信号量”）。</p>
<p>我们沿用文章<a href="https://fengxun2017.github.io/2022/12/17/FreeRTOS-use-counting-semaphore/">FreeRTOS-使用计数信号量</a>中使用计数信号量来记录按键次数的例子。使用<code>Task Notification</code>模拟计数信号量，并记录按键次数。这样，任务即使因为忙，无法立即响应短时间内发生的多次按键，但由于事件发生的次数已经被记录，使得任务在忙完之后仍旧能够感知到每个发生的事件。</p>
<p>按键中断函数，以及main 函数均不用改动，沿用上文的代码。<br>按键处理任务修改如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">void</span> <span class="title function_">button_pressed_handler</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        <span class="comment">// 这里等待时间使用portMAX_DELAY，表示一直等待直到可用。</span></span><br><span class="line">        <span class="comment">// 使用portMAX_DELAY，需要在FreeRTOSConfig.h 文件中定义 INCLUDE_vTaskSuspend = 1</span></span><br><span class="line">        <span class="comment">// 正式产品代码最好使用一个超时值，这样异常发生时（中断源发生异常，没按预期触发），至少能获得超时错误，可以在超时错误中做一些恢复操作。</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">// xClearCountOnExit = pdFALSE，使得每次获得“信号量”后，“信号量”的计数值仅递减</span></span><br><span class="line">        ulTaskNotifyTake(pdFALSE, portMAX_DELAY);</span><br><span class="line"></span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in task, do something\n&quot;</span>);</span><br><span class="line">        <span class="comment">// 阻塞任务2秒，模拟在做其它工作，如果这期间发生了 n 次按键事件，事件的次数会记录在内部</span></span><br><span class="line">        <span class="comment">// 之后对应可以无阻塞的调用ulTaskNotifyTake n 次，使得每次事件都有对应的一次处理。  </span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行如下：在按键处理任务正在做其它工作时，这期间发生了三次按键，由于按键处理任务正在“忙”，无法立即响应。但事件发生的次数被记录下来了。并在之后，任务会依次处理每个发生过的事件。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">in interrupt service function, button pressed</span><br><span class="line">in task, do something</span><br><span class="line">in interrupt service function, button pressed</span><br><span class="line">in task, do something</span><br><span class="line">in interrupt service function, button pressed   #在按键处理任务正在做其它工作时，这期间发生了三次按键，并被记录下来。</span><br><span class="line">in interrupt service function, button pressed</span><br><span class="line">in interrupt service function, button pressed</span><br><span class="line">in task, do something   #之后，根据记录的次数，调用相应次数的处理过程</span><br><span class="line">in task, do something</span><br><span class="line">in task, do something</span><br></pre></td></tr></table></figure>


<h4 id="3-使用Task-Notifacation-模拟-event-group"><a href="#3-使用Task-Notifacation-模拟-event-group" class="headerlink" title="3 使用Task Notifacation 模拟 event group"></a>3 使用Task Notifacation 模拟 event group</h4><p>在32位MCU中，<a href="https://fengxun2017.github.io/2023/01/13/FreeRTOS-event-group/">event group</a>本质就是一个<code>uint32_t</code>数值，其高8位是内部使用的控制位，不可以使用。低24位开发者可以使用，开发者可以使用其中的任意一个位来表示一个自定义的事件。<br>任务可以等待某个事件发生（等待相应位被置位），等待多个事件同时发生（等待多个位同时被置位），或者等待多个事件中的任意一个事件发生（等待多个位中任意一个被置位）。</p>
<p><code>Task Notification</code>的<code>ulNotifiedValue</code>也是一个<code>uint32_t</code>数值，我们也可以使用其中的位，表示一些自定义的事件，来实现模拟<code>event group</code>的功能。</p>
<p>使用<code>Task Notification</code>来模拟<code>event group</code>时，使用 API:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xTaskNotifyWait</span><span class="params">( <span class="type">uint32_t</span> ulBitsToClearOnEntry,</span></span><br><span class="line"><span class="params">                            <span class="type">uint32_t</span> ulBitsToClearOnExit,</span></span><br><span class="line"><span class="params">                            <span class="type">uint32_t</span> *pulNotificationValue,</span></span><br><span class="line"><span class="params">                            TickType_t xTicksToWait )</span>;</span><br></pre></td></tr></table></figure>
<p>可以实现“等待事件发生”功能。<br>其中：</p>
<ul>
<li><strong>ulBitsToClearOnEntry</strong>：用来指定在开始等待前，哪些位需要清除。例如，应用中存在一个交易功能，在发起交易后，调用xTaskNotifyWait来等待按键事件。这种情况下设置ulBitsToClearOnEntry&#x3D;1&lt;&lt;n（第n位表示按键事件），使得等待前确保按键事件位被清零，避免之前遗留的数据对这里按键事件造成误判。</li>
<li><strong>ulBitsToClearOnExit</strong>：当收到其它任务发送的notification数据后，任务解除阻塞恢复就绪，同时会自动清零任务控制块中<code>ulNotifiedValue</code>的那些由<code>ulBitsToClearOnExit</code>指定的位。（等待的事件发生之后，清除事件标记位，避免重复触发）</li>
<li><strong>pulNotificationValue</strong>：当函数返回时（收到数据或等待超时），会将任务控制块中当前的<code>ulBitsToClearOnExit</code>值保存在该参数中。（注意，是保存之后，才会根据第二个参数 ulBitsToClearOnExit 来清零需要清零的位）</li>
<li><strong>xTicksToWait</strong>：最长等待时间。</li>
<li><strong>返回值</strong>：返回<code>pdTRUE</code>表示收到数据，返回<code>pdFALSE</code>表示等待超时。</li>
</ul>
<p>而设置事件，则通过<code>Task Notification</code>的发送 notification 数据来实现：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xTaskNotify</span><span class="params">( TaskHandle_t xTaskToNotify, </span></span><br><span class="line"><span class="params">                        <span class="type">uint32_t</span> ulValue, </span></span><br><span class="line"><span class="params">                        eNotifyAction eAction )</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li><strong>xTaskToNotify</strong>：目标任务的句柄。</li>
<li><strong>ulValue</strong>：需要发送的值</li>
<li><strong>eAction</strong>：对于模拟<code>event group</code>来说，设置<code>eAction = eSetBits</code>，表示根据参数<code>ulValue</code>设置目标任务<code>ulNotifiedValue</code>中的相应位（表示这些位对应的自定义事件发生了）。</li>
</ul>
<p>需要注意的是，<code>Task Notification</code>的等待数据 API：<code>xTaskNotifyWait</code>，在收到<strong>任意数据</strong>时后就会返回（解除阻塞状态），因此用该函数无法实现<code>event group</code>的等待多个事件同时发生才返回的特性。</p>
<p>我们使用<code>Task Notification</code>作为<code>event group</code>来实现下面的例子：<br>每当<code>task_a</code>完成一些特定工作，就会设置事件<code>TASK_A_DONE</code><br>每当<code>task_b</code>完成一些特定工作，就会设置事件<code>TASK_B_DONE</code><br><code>task_c</code>等待<code>TASK_A_DONE</code>、<code>TASK_B_DONE</code>任意一个事件发生，则执行相关处理，代码如下所示：</p>
<p>任务代码：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 使用第 0 位来表示事件：task_a工作执行完</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> TASK_A_DONE_FLAG ( 1 &lt;&lt; 0 )    </span></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_a</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    TaskHandle_t  task_c = (TaskHandle_t)pvParameters;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 延迟1秒，模拟 task_a 在处理一些工作</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_a done!\n&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 工作做完了，设置事件对应的位，通知task_c</span></span><br><span class="line">        xTaskNotify(task_c, TASK_A_DONE_FLAG, eSetBits);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 使用第 1 位来表示事件：task_b工作执行完</span></span><br><span class="line"><span class="meta">#<span class="keyword">define</span> TASK_B_DONE_FLAG ( 1 &lt;&lt; 1 )    </span></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    TaskHandle_t  task_c = (TaskHandle_t)pvParameters;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 延迟1秒，模拟 task_b 在处理一些工作</span></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">1000</span>));</span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_b done!\n&quot;</span>);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 工作做完了，设置事件对应的位，通知task_c</span></span><br><span class="line">        xTaskNotify(task_c, TASK_B_DONE_FLAG, eSetBits);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_c</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="type">uint32_t</span> notification_value;</span><br><span class="line">    BaseType_t ret;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 这里等待事件（task_a 或 task_b 完成工作）</span></span><br><span class="line">        <span class="comment">// task_c 会阻塞在该函数内部，直到事件发生，或者等待超过2秒</span></span><br><span class="line">        ret = xTaskNotifyWait(<span class="number">0</span>, TASK_A_DONE_FLAG|TASK_B_DONE_FLAG, &amp;notification_value, pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">        <span class="keyword">if</span> (pdTRUE == ret) &#123;</span><br><span class="line">            <span class="keyword">if</span> (notification_value &amp; TASK_A_DONE_FLAG) &#123;</span><br><span class="line">                SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in task_c: task_a done!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// do something</span></span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (notification_value &amp; TASK_B_DONE_FLAG) &#123;</span><br><span class="line">                SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;in task_c: task_b done!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">                <span class="comment">// do something</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>main函数实现如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdint.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdbool.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;SEGGER_RTT.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    TaskHandle_t  taskc_handle;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pdPASS == xTaskCreate(task_c, <span class="string">&quot;task_c&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">1</span>, &amp;taskc_handle)</span><br><span class="line">        &amp;&amp; pdPASS == xTaskCreate(task_a, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, taskc_handle, <span class="number">1</span>, <span class="literal">NULL</span>)</span><br><span class="line">        &amp;&amp; pdPASS == xTaskCreate(task_b, <span class="string">&quot;task_b&quot;</span>, <span class="number">100</span>, taskc_handle, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">        </span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">        vTaskStartScheduler();</span><br><span class="line">    &#125; </span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>


<p>运行结果如下所示：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">task_a done!</span><br><span class="line">task_b done!</span><br><span class="line">in task_c: task_a done!</span><br><span class="line">in task_c: task_b done!</span><br><span class="line">task_a done!</span><br><span class="line">task_b done!</span><br><span class="line">in task_c: task_a done!</span><br><span class="line">in task_c: task_b done!</span><br><span class="line">task_a done!</span><br><span class="line">task_b done!</span><br><span class="line">in task_c: task_a done!</span><br><span class="line">in task_c: task_b done!</span><br></pre></td></tr></table></figure>

<h4 id="使用Task-Notifacation-作为一个轻量级消息邮箱"><a href="#使用Task-Notifacation-作为一个轻量级消息邮箱" class="headerlink" title="使用Task Notifacation 作为一个轻量级消息邮箱"></a>使用Task Notifacation 作为一个轻量级消息邮箱</h4><p>如上一节文所述，任务控制块中的<code>ulNotifiedValue</code>为一个<code>uint32_t</code>数值，我们可以将其作为一个4字节的存储空间，因此每次可以发送单个<code>uint32_t</code>数值，或发送4个<code>char</code>类型数值，使其成为一个轻量级的消息邮箱（消息直接发送给目标，不需要创建额外对象，非常适合在任务间传递数值，或几个字节的数据）。</p>
<p>对于发送notification的 API</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">BaseType_t <span class="title function_">xTaskNotify</span><span class="params">( TaskHandle_t xTaskToNotify, </span></span><br><span class="line"><span class="params">                        <span class="type">uint32_t</span> ulValue, </span></span><br><span class="line"><span class="params">                        eNotifyAction eAction )</span>;</span><br></pre></td></tr></table></figure>
<p>其参数<code>eAction</code>除了可以设置为上一节所述为<code>eSetBits</code>，使其能单独设置某些位。<br>还可以设置为：</p>
<ul>
<li><strong>eIncrement</strong>：让目标任务的<code>ulNotifiedValue</code>值自增1。实际上前文所述的<code>xTaskNotifyGive</code>就是一个宏，其本质就是使用<code>eAction= eIncrement</code>的<code>xTaskNotify</code>。</li>
<li><strong>eSetValueWithOverwrite</strong>：设置目标任务的<code>ulNotifiedValue</code>值为参数中的<code>ulValue</code>。</li>
<li><strong>eSetValueWithoutOverwrite</strong>：同上，但如果目标任务没有读取过上一次设置的值，则本次不会执行写入。</li>
</ul>
<p>因此，发送Notification时，将<code>xTaskNotify</code>参数<code>eAction</code>设置为<code>eSetValueWithOverwrite</code>或<code>eSetValueWithoutOverwrite</code>即可用<code>Task Notification</code>作为轻量级邮箱使用。</p>
<p>如下所示样例:<br>创建任务<code>task_a</code>，周期性地向任务<code>task_b</code>发送数据。（例如周期采样某个传感器数据，发送给任务，如果是中断服务函数中向目标任务发送数据，需要使用发送函数的中断版本<code>xTaskNotifyFromISR</code>）</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdint.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdbool.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;task.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;FreeRTOS.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&quot;SEGGER_RTT.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_a</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    TaskHandle_t  task_c = (TaskHandle_t)pvParameters;</span><br><span class="line">    <span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 将 i 值发送给 task_b</span></span><br><span class="line">        xTaskNotify(task_c, i++, eSetValueWithOverwrite);</span><br><span class="line"></span><br><span class="line">        vTaskDelay(pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">void</span> <span class="title function_">task_b</span><span class="params">( <span class="type">void</span> *pvParameters )</span> &#123;</span><br><span class="line">    </span><br><span class="line">    <span class="type">uint32_t</span> notification_value;</span><br><span class="line">    BaseType_t ret;</span><br><span class="line">    <span class="keyword">for</span>(;;) &#123;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// task_b 会阻塞在该函数内部，直到收到数据，或者等待超过2秒</span></span><br><span class="line">        <span class="comment">// ulBitsToClearOnExit=0xffffffff，表示读取完ulNotifiedValue的之后，将其清零。</span></span><br><span class="line">        ret = xTaskNotifyWait(<span class="number">0</span>, <span class="number">0xffffffff</span>, &amp;notification_value, pdMS_TO_TICKS(<span class="number">2000</span>));</span><br><span class="line">        <span class="keyword">if</span> (pdTRUE == ret) &#123;</span><br><span class="line">            SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;task_b recv: %u\n&quot;</span>, notification_value);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">void</span>)</span> &#123;</span><br><span class="line">    </span><br><span class="line">    bsp_init();</span><br><span class="line">    TaskHandle_t  taskb_handle;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (pdPASS == xTaskCreate(task_b, <span class="string">&quot;task_b&quot;</span>, <span class="number">100</span>, <span class="literal">NULL</span>, <span class="number">1</span>, &amp;taskb_handle)</span><br><span class="line">        &amp;&amp; pdPASS == xTaskCreate(task_a, <span class="string">&quot;task_a&quot;</span>, <span class="number">100</span>, taskb_handle, <span class="number">1</span>, <span class="literal">NULL</span>))&#123;</span><br><span class="line">        </span><br><span class="line">        SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;start FreeRTOS\n&quot;</span>);</span><br><span class="line">        vTaskStartScheduler();</span><br><span class="line">    &#125; </span><br><span class="line"></span><br><span class="line">    <span class="comment">// 正常启动后不会运行到这里</span></span><br><span class="line">    SEGGER_RTT_printf(<span class="number">0</span>, <span class="string">&quot;insufficient resource\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">    <span class="keyword">for</span>( ;; );</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


<p>运行输出如下：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">start FreeRTOS</span><br><span class="line">task_b recv: 0</span><br><span class="line">task_b recv: 1</span><br><span class="line">task_b recv: 2</span><br><span class="line">task_b recv: 3</span><br></pre></td></tr></table></figure>

<br>
<br>
ps：需要注意文章代码中的日志输出函数，产品代码中如果需要使用的话，需要考虑多线程安全性（多任务安全性），因为中断/任务切换可能发生在另一个任务正在输出日志但还未输出完的时候，这就可能造成日志错乱

<br>
<br>
FreeRTOS交流QQ群-663806972
    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>feng xun
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="http://fengxun2017.github.io/2023/02/13/FreeRTOS-use-task-notification/" title="FreeRTOS-使用 task notification">http://fengxun2017.github.io/2023/02/13/FreeRTOS-use-task-notification/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/02/07/FreeRTOS-task-notification/" rel="prev" title="FreeRTOS-Task Notification">
                  <i class="fa fa-chevron-left"></i> FreeRTOS-Task Notification
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/02/16/memory-ordering-MESI/" rel="next" title="缓存一致性协议MESI">
                  缓存一致性协议MESI <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">feng xun</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">552k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">11:30</span>
  </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  





  





</body>
</html>
